<?php
/*
*author:TT
*createtime:2017/3/7 18:56
*description:
*/
namespace haibao\jiepai\data;

use haibao\frame\data\query\Condition;

class Album extends \haibao\jiepai\data\BaseMysql
{

    public function __construct()
    {
        parent::__construct('\haibao\jiepai\model\data\user\CmsUserAlbums');
    }

    public function setAlbumToTop($pkId, $type)
    {
        $this->query('update cms_user_albums_hot set IsTop=%s where ID=%s', array(
            $type, $pkId
        ));
    }

    public function deleteHotAlbum($pkId)
    {
        $this->query('delete from cms_user_albums_hot where ID=%s', array(
            $pkId
        ));
    }

    public function getAlbumById($albumId)
    {
        return $this->query('select * from cms_user_albums where Flag=0 and AlbumID=%s limit 1', array(
            $albumId
        ))->fetch_assoc();
    }

    public function CreateAlbum($model)
    {
        $this->add($model);
        return $model->Id;
    }

    public function getAlbums($albumId)
    {
        $result = $this->query('select a.*,c.NickName,count(*) as PictureCount from (select * from cms_user_albums where AlbumID=%s ) a left join cms_album_pictures as b on a.AlbumID=b.AlbumID left join cms_users as c on a.UserID=c.UserID where b.FileID!="" and b.Flag=0', array(
            intval($albumId)
        ))->fetch_assoc();
        if (isset($result['AlbumID'])) {
            $result['AlbumID'] = intval($result['AlbumID']);
        }
        if (isset($result['UserID'])) {
            $result['UserID'] = intval($result['UserID']);
        }
        if (isset($result['PictureCount'])) {
            $result['PictureCount'] = intval($result['PictureCount']);
        }
        if (isset($result['Type'])) {
            $result['IsDefault'] = intval($result['Type']);
            unset($result['Type']);
        }
        if (isset($result['IsPrivate'])) {
            $result['IsPrivate'] = intval($result['IsPrivate']);
        }
        return $result;
    }

    public function getAlbumInfoByUserId($userId)
    {
        $albumInfo = $this->query('select c.*,count(*) as PictureCount from (select distinct(a.UserID),a.NickName,count(*) as TotalAlbumCount,sum(b.ViewNum) as TotalViews,Type as IsDefault,IsPrivate from cms_users as a left join cms_user_albums as b on a.UserID=b.UserID where a.UserID=%s and b.Flag=0 and IsPrivate=0) c inner join cms_album_pictures as d on c.UserID=d.UserID and d.Flag=0', array(
            $userId
        ))->fetch_assoc();
        if (isset($albumInfo['UserID'])) {
            $albumInfo['UserID'] = intval($albumInfo['UserID']);
        }
        if (isset($albumInfo['TotalAlbumCount'])) {
            $albumInfo['TotalAlbumCount'] = intval($albumInfo['TotalAlbumCount']);
        }
        if (isset($albumInfo['TotalViews'])) {
            $albumInfo['TotalViews'] = intval($albumInfo['TotalViews']);
        }
        if (isset($albumInfo['PictureCount'])) {
            $albumInfo['PictureCount'] = intval($albumInfo['PictureCount']);
        }
        if (isset($albumInfo['IsDefault'])) {
            $albumInfo['IsDefault'] = intval($albumInfo['IsDefault']);
        }
        if (isset($albumInfo['IsPrivate'])) {
            $albumInfo['IsPrivate'] = intval($albumInfo['IsPrivate']);
        }
        $albumInfo['Avatar'] = '';
        return $albumInfo;
    }

    public function getHotAlbumList($cursor = null)
    {
        if (!$cursor) {
            $sql = 'select a.Id,a.AlbumID,a.AlbumName,a.UserID,a.NickName,b.ViewNum as TotalViews,a.NewestPicture from cms_user_albums_hot as a left join cms_user_albums as b on a.AlbumID=b.AlbumID where b.IsPrivate!=1 order by IsTop desc, rand() limit 30';
            $result = $this->query($sql);
        } else {
            $cursor = intval($cursor) - 1;
            $result = $this->query('select a.Id,a.AlbumID,a.AlbumName,a.UserID,a.NickName,b.ViewNum as TotalViews,a.NewestPicture from cms_user_albums_hot as a left join cms_user_albums as b on a.AlbumID=b.AlbumID where b.IsPrivate!=1 and a.Id>%s and IsTop!=1 order by a.UpdateTime desc,a.Id asc limit 30', array(intval($cursor)));
        }
        $albumRet = array();
        while ($row = $result->fetch_assoc()) {
            $row['Id'] = intval($row['Id']);
            $row['AlbumID'] = intval($row['AlbumID']);
            $row['UserID'] = intval($row['UserID']);
            $row['TotalViews'] = intval($row['TotalViews']);
            $row['Avatar'] = '';
            $row['Pictures'] = explode(',', $row['NewestPicture']);
            unset($row['NewestPicture']);
            array_push($albumRet, $row);
        }
        return $albumRet;
    }

    public function getNewestPictureByIds($imageIds)
    {
        $imageIds = array_filter(array_unique($imageIds));
        $imageIds = implode(',', $imageIds);
        return self::mergeDataAndImage($imageIds, null, true);
    }

    /**
     * 根据相册ID取最新的三张图片
     * @param $albumIds
     * @return array
     */
    public function getNewestPicture($albumIds)
    {
        if (!$albumIds) {
            return array();
        }
        $cache = new \haibao\jiepai\cache\Album();
        $data = new \haibao\cms\data\ImageLibrary();
        $pictureList = array();
        foreach ($albumIds as $key => $albumId) {
            $imageInfo = array();
            $imageInfo = $cache->getNewestPicture($albumId);
            if (!$imageInfo) {
                $result = $this->query('select FileID from cms_album_pictures where AlbumID=%s and Flag=0 order by CreateTime desc limit 3', array($albumId));
                $list = array();
                while ($row = $result->fetch_assoc()) {
                    array_push($list, $row);
                }
                $imageInfo = self::mergeDataAndImage($list, 'FileID');
                $cache->setNewestPicture($albumId, $imageInfo);
            }
            $pictureList[$albumId] = $imageInfo;
        }
        return $pictureList;
    }

    /**
     * 根据相册ID查询相册内图片列表
     * @param $albumId
     */
    public function getPictureByAlbumId($albumId, $cursor = null)
    {
        if ($cursor) {
            $result = $this->query('select Id,ContentID,FileID,UserID,CreateTime from cms_album_pictures where AlbumID=%s and Flag=%s and CreateTime<%s and FileID!="" order by CreateTime desc limit 30', array(
                $albumId, 0, $cursor, 0
            ));
        } else {
            $result = $this->query('select Id,ContentID,FileID,UserID,CreateTime from cms_album_pictures where AlbumID=%s and Flag=%s and FileID!="" order by CreateTime desc limit 30', array(
                $albumId, 0
            ));
        }
        $pictureList = array();
        while ($row = $result->fetch_assoc()) {
            array_push($pictureList, $row);
        }
        return self::mergeDataAndImage($pictureList, 'FileID');
    }

    /**
     * 根据用户ID查询相册列表，按时间倒序排序
     * @param $userId
     */
    public function getAlbumList($userId, $includePrivate = false)
    {
        $cache = new \haibao\jiepai\cache\Album();
        if($includePrivate){
//            $sql = 'select b.ID as AlbumPictureID, a.AlbumID,a.UserID,a.AlbumName,ViewNum as TotalViews,count(*) as PictureCount,a.`Type` as IsDefault,IsPrivate from cms_user_albums as a left join cms_album_pictures as b on a.AlbumID=b.AlbumID and b.Flag=0 and b.FileID!="" where a.Flag=0 and a.UserID=%s group by a.AlbumID order by a.Type desc,a.CreateTime ASC';
            $sql = 'select *,count(*) as PictureCount from (
                        select a.AlbumID,a.AlbumName,b.CreateTime,b.ID as AlbumPictureID,a.UserID,a.ViewNum as TotalViews,a.`Type` as IsDefault,IsPrivate from cms_user_albums as a left join cms_album_pictures as b on a.AlbumID=b.AlbumID and a.Flag=0 and b.Flag=0 and b.FileID!="" where a.Flag=0 and a.UserID=%s order by b.CreateTime desc
                    ) c  group by c.AlbumID order by c.CreateTime desc';
        }else{
//            $sql = 'select b.ID as AlbumPictureID, a.AlbumID,a.UserID,a.AlbumName,ViewNum as TotalViews,count(*) as PictureCount,a.`Type` as IsDefault,IsPrivate from cms_user_albums as a inner join cms_album_pictures as b on a.AlbumID=b.AlbumID and b.Flag=0 and b.FileID!="" where a.Flag=0 and a.UserID=%s and a.IsPrivate=0 group by a.AlbumID order by a.Type desc,a.CreateTime ASC';
            $sql = 'select *,count(*) as PictureCount from (
                        select a.AlbumID,a.AlbumName,b.CreateTime,b.ID as AlbumPictureID,a.UserID,a.ViewNum as TotalViews,a.`Type` as IsDefault,IsPrivate from cms_user_albums as a left join cms_album_pictures as b on a.AlbumID=b.AlbumID and a.Flag=0 and b.Flag=0 and b.FileID!="" where a.Flag=0 and a.UserID=%s and a.IsPrivate=0 order by b.CreateTime desc
                    ) c  group by c.AlbumID order by c.CreateTime desc';
        }
        $result = $this->query($sql, array(
            $userId
        ));
        $albumList = array();
        $albumIds = array();
        while ($row = $result->fetch_assoc()) {
            $row['PictureCount'] = (!is_null($row['AlbumPictureID'])) ? intval($row['PictureCount']) : 0;
            $row['AlbumID'] = intval($row['AlbumID']);
            $row['UserID'] = intval($row['UserID']);
            $row['TotalViews'] = intval($row['TotalViews']);
            $row['IsDefault'] = intval($row['IsDefault']);
            $row['AlbumName'] = $row['AlbumName'];
            $row['IsPrivate'] = intval($row['IsPrivate']);
            $row['AlbumCover'] = '';
            array_push($albumList, $row);
            array_push($albumIds, $row['AlbumID']);
        }

        if ($albumIds) {
            $str = preg_replace('/(\d+)/', '%s', implode(',', $albumIds));
            $sql = 'select * from (SELECT AlbumID,FileID, CreateTime FROM cms_album_pictures WHERE AlbumID IN (' . $str . ') AND Flag = 0 order by CreateTime  desc) a group by a.AlbumID ';
            $result = $this->query($sql, $albumIds);

            $pictureArr = array();
            while ($row = $result->fetch_assoc()) {
                array_push($pictureArr, $row);
            }

            $imageList = self::mergeDataAndImage($pictureArr, 'FileID');

            $imageArr = array();
            if ($imageList) {
                foreach ($imageList as $Key => &$image) {
                    if (empty($image['Picture'])){
                        continue;
                    }
                    $albumId = $image['AlbumID'];
                    unset($image['AlbumID'], $image['CreateTime'], $image['CropX'], $image['CropY'], $image['CropWidth'], $image['CropHeight'], $image['Size'], $image['FileDescription']);
                    $imageArr[$albumId] = $image;
                }
            }
            foreach ($albumList as $key => &$album) {
                $album['AlbumCover'] = isset($imageArr[$album['AlbumID']]) ? $imageArr[$album['AlbumID']] : null;
            }
        }
        return $albumList;
    }

    /**
     * 根据用户ID查询图片列表，按收藏时间倒序排序
     * @param $userId
     */
    public function getImageList($userId, $cursor = null)
    {
        if ($cursor) {
            $sql = 'select * from cms_album_pictures where UserID="' . $userId . '" and Flag=0 and CreateTime<"' . $cursor . '" order by CreateTime desc limit 30';
        } else {
            $sql = 'select * from cms_album_pictures where UserID="' . $userId . '" and Flag=0 order by CreateTime desc limit 30';
        }
        $result = $this->query($sql);

        $imageList = array();
        while ($row = $result->fetch_assoc()) {
            unset($row['ID'], $row['Type'], $row['ArticleID'], $row['UserID'], $row['FileName'], $row['Flag']);
            array_push($imageList, $row);
        }
        return self::mergeDataAndImage($imageList, 'FileID');
    }

    /**
     * 获取相册内图片
     * @param $albumId
     * @param int $count
     * @param null $cursor
     * @return array
     */
    public function getAlbumPicture($albumId, $count = 1, $cursor = null)
    {
        $query = new \haibao\jiepai\model\filter\user\CmsAlbumPictures();
        $query->select(array(
            $query::CONDITION_FIELD_NAME_ALBUM_ID,
            $query::CONDITION_FIELD_NAME_FILE_ID,
        ))
            ->where($query::CONDITION_FIELD_NAME_ALBUM_ID, Condition::CONDITION_EQUAL, $albumId)
            ->order($query::CONDITION_FIELD_NAME_CREATE_TIME, false)
            ->setPager(new \haibao\frame\data\query\Pager($count, 1));

        if ($cursor) {
            $query->where($query::CONDITION_FIELD_NAME_CREATE_TIME, Condition::CONDITION_LESS, $cursor);
        }
        $result = $this->getAll($query);

        $fileList = array();
        if ($result) {
            foreach ($result as $key => $value) {
                $tmp['FileID'] = $value->FileID;
                array_push($fileList, $tmp);
            }
        }

        $albumPicture = self::mergeDataAndImage($fileList, 'FileID');
        if ($albumPicture) {
            foreach ($albumPicture as $key => &$picture) {
                $picture['PictureID'] = $picture['FileID'];
                unset($picture['CropX'], $picture['CropY'], $picture['CropWidth'], $picture['CropHeight'], $picture['Ratio'], $picture['FileID']);
            }
        }
        return $albumPicture;
    }

    /**
     * 根据年月分组取收藏图片数量
     */
    public function getPictureCountGroupByDate($albumUserId)
    {
        $result = $this->query('select DATE_FORMAT(CreateTime,"%s") as date,count(*) as count from cms_album_pictures where UserID=%s and Flag=0 group by date desc', array(
            '%Y%m', $albumUserId
        ));
        $retArr = array();
        while ($row = $result->fetch_assoc()) {
            $retArr[trim($row['date'], "'")] = $row['count'];
        }
        return $retArr;
    }

    public function authAlbumName($userId, $albumName)
    {

        $sql = "SELECT AlbumID from cms_user_albums WHERE Flag = 0 AND UserID=%s AND AlbumName=%s";
        return $this->query($sql, array($userId, $albumName))->fetch_assoc();
    }

    public function CreateNewAlbum($userId, $albumName)
    {
        $sql = "insert into cms_user_albums (UserID,AlbumName) values (%s,%s)";
        $result = $this->query($sql, array($userId, $albumName));
        return $this->getDb()->insert_id;
    }

    public function CheckAlbumIsDefault($albumId)
    {

        $sql = "SELECT Count(*) as count,UserID from cms_user_albums WHERE AlbumID=%s AND Type = 1";
        $result = $this->query($sql, array($albumId))->fetch_assoc();
        return $result ? $result['count'] : 0;
    }

    public function getAlbumInfo($albumId, $userId)
    {

        $sql = "SELECT * from cms_user_albums WHERE Flag = 0 AND UserID = %s AND AlbumID = %s";
        return $this->query($sql, array($userId, $albumId))->fetch_assoc();
    }

    public function delAlbum($albumId, $userId)
    {
        if(!$albumId || !$userId){
            return false;
        }
        $sql = "UPDATE cms_user_albums SET Flag=-1 where Flag = 0 AND AlbumID = %s AND UserID = %s limit 1";
        $this->query($sql, array($albumId, $userId));
        $this->query('update cms_album_pictures set Flag=-1 where AlbumID = %s AND UserID = %s ', array($albumId, $userId));
    }

    public function updateAlbum($albumName, $userId, $albumId, $isPrivate = 0)
    {
        $sql = "UPDATE cms_user_albums SET AlbumName=%s,IsPrivate=%s where Flag = 0 AND AlbumID = %s AND UserID = %s limit 1";
        $this->query($sql, array($albumName, $isPrivate, $albumId, $userId ));
    }
    
    public function updateAlbumStatistic($albumId){
        $sql = "UPDATE cms_user_albums SET ViewNum=ViewNum+1 WHERE AlbumID = %s limit 1";
        $this->query($sql, array($albumId));
    }

    /**
     * 创建默认相册
     * @param $model
     */
    public function createDefaultAlbum($model){
        $this->add($model);
    }
}
